﻿
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SY.BasicData.Infrastructures
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="T">实体</typeparam>

    public class BaseRepository<T> : IBaseRepository<T> where T : class
    { /// <summary>
      /// 上下文
      /// </summary>
        private readonly DBDbContext db;
        /// <summary>
        ///构造函数
        /// </summary>
        /// <param name="db">上下文</param>
        public BaseRepository(DBDbContext db)
        {
            this.db = db;
        }

        public DBDbContext DB
        { get { return db; } }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>返回受影响的函数</returns>

        public async Task<int> Add(T t)
        {
            await db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync();
        }

        public async Task<int> AddRange(List<T> t)
        {
            await db.Set<T>().AddRangeAsync(t);
            return await db.SaveChangesAsync();
        }

        public async Task<int> Delete(List<T> t)
        {
            db.Set<T>().RemoveRange(t);
            return await db.SaveChangesAsync();
        }

     

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns>返回结果</returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>返回受影响的函数</returns>
        public async Task<int> Update(T t)
        {
            db.Set<T>().Update(t);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改批量操作
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> UpdateRange(List<T> t)
        {
            db.Set<T>().UpdateRange(t);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 查询第一条数据
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> predicate)
        {
            return await db.Set<T>().FirstOrDefaultAsync(predicate);
        }

    }
}
